package com.example.myapplication.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.myapplication.R;
import com.example.myapplication.db.Data;
import com.example.myapplication.db.DataJson;
import com.example.myapplication.db.SQLiteManager;
import com.karonl.instance.Adapter.DataAdapter;
import com.karonl.instance.InDoorView;
import com.karonl.instance.Interface.FramesListener;
import com.karonl.instance.Unit.PathUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PlaneFragment extends Fragment {
    private SQLiteDatabase db;
    private SQLiteManager helper;
    private Context mContext = null;
    private Activity mActivity = null;
    private TextView axis_x;
    private TextView axis_y;
    private String GatewayID;
    private String GatewayType;
    private String[] NodeNameArray;//保存节点ID
    private String area = null;
    private HashMap<String, String> Sites = new HashMap<String, String>(); //根据节点ID索引其坐标
    private MainFragment.MainFragmentListener listener;

    public PlaneFragment() {
    }

    private DataAdapter adapter = new DataAdapter();
    private Bitmap bmp;
    private String[] areaSpilt;
    List<PathUnit> unitList = new ArrayList<>();

    private NewHandler handler = new NewHandler(this);

    private static class NewHandler extends Handler {
        private WeakReference<PlaneFragment> weakReference;

        public NewHandler(PlaneFragment main) {
            weakReference = new WeakReference<>(main);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (weakReference.get() != null) {
                float fr = (float) (msg.arg1);
//                if (fr == 1000f) {
//                    weakReference.get().textView.setText("FPS: stop");
//                } else {
//                    float fps = (int) (1000f / fr);
//                    weakReference.get().textView.setText("FPS: " + fps + "");
//                }
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_plane,container,false);
        mContext = getContext();
        mActivity = getActivity();
        helper = new SQLiteManager(mContext);
        NodeNameArray = new String[50];

        return view;
    }

    @SuppressLint("Range")
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        axis_x = (TextView) mActivity.findViewById(R.id.axis_x);
        axis_y = (TextView) mActivity.findViewById(R.id.axis_y);

        if(getArguments() != null){
            GatewayID = getArguments().getString(Data.COLUMN_Gateway);
            GatewayType = getArguments().getString(Data.COLUMN_GatewayType);
        }

        /**
         * 查询所有的节点并保存
         * */
        db = helper.getReadableDatabase();
        Cursor cursor1 = db.query(Data.NodeLocal_Table, null,
                Data.COLUMN_Gateway +"=?", new  String[]{ GatewayID }, null, null, null);
        if(cursor1.moveToFirst()){
            int i = 0;
            do{
                NodeNameArray[i] = cursor1.getString(cursor1.getColumnIndex(Data.COLUMN_NodeName));
                area = cursor1.getString(cursor1.getColumnIndex(Data.COLUMN_Area));
                Sites.put(NodeNameArray[i], cursor1.getString(cursor1.getColumnIndex(Data.COLUMN_LocalInfo)));
                i++;
            }while (cursor1.moveToNext());
        }
        cursor1.close();

        if(area != null){
            areaSpilt = area.split("_");
            axis_x.setText(areaSpilt[0]);
            axis_y.setText(areaSpilt[1]);
            startView();
        }else {
            Toast.makeText(mContext, "没有位置信息", Toast.LENGTH_SHORT).show();
        }

    }

    public static  PlaneFragment newInstance(Bundle bundle){
        PlaneFragment fragment = new PlaneFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    private void getUnitList() {
        DataJson data = new DataJson(NodeNameArray, Sites, areaSpilt);
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject = data.getArray(i);
            PathUnit unit = new PathUnit(getList(jsonObject));
            try {
                unit.setName(jsonObject.getString("name"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            unitList.add(unit);
        }
    }

    //每个图案的坐标组合
    private List<PointF> getList(JSONObject jsonObject) {
        float density = getResources().getDisplayMetrics().density;
        List<PointF> pointList = new ArrayList<>();
        JSONArray array;
        try {
            array = jsonObject.getJSONArray("area");
            for (int r = 0; r < array.length(); r++) {
                float x = ((JSONObject) (array.get(r))).getInt("x");
                float y = ((JSONObject) (array.get(r))).getInt("y");
                pointList.add(new PointF(x * density, y * density));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return pointList;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try{
            listener = (MainFragment.MainFragmentListener) context;
        }catch(ClassCastException e){
            e.printStackTrace();
        }
    }

    public void startView(){
        /**
         * 根据前面查到的节点
         */

        InDoorView view = (InDoorView) mActivity.findViewById(R.id.surface);

        //延迟展区区域数据加载
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                }

                //背景图
                BitmapFactory.Options opt = new BitmapFactory.Options();
                opt.inPreferredConfig = Bitmap.Config.RGB_565;
                bmp = BitmapFactory.decodeResource(getResources(), R.drawable.map_test, opt);//图片资源
                adapter.setBmp(bmp);//设置图片
                bmp = null;
                getUnitList();//设置数组

                if(!unitList.isEmpty()){
                    adapter.setList(unitList);//设置数组
                    adapter.refreshData();
                }

                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mActivity.findViewById(R.id.tip).setVisibility(View.GONE);
                    }
                });
            }
        }).start();

        view.setAdapter(adapter);//初始化

        view.setOnClickMapListener(new InDoorView.onClickMapListener() {
            @Override
            public void onClick(PathUnit region) {
//                Log.e(this.getClass().getName(), "click");
//                AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
//                dialog.setTitle("商店介绍");
//                dialog.setMessage("" + region.getName());
//                dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });
                Bundle bundle = new Bundle();
                db = helper.getReadableDatabase();
                Cursor cursor1 = db.query(Data.NodeArray_Table, null, Data.COLUMN_Gateway +
                        "=?", new String[]{GatewayID}, null, null, null);
                String SensorTypeArray = null;
                int sensorNum = 0;
                boolean a = true;

                if(cursor1.moveToFirst()){
                    do{
                        if(cursor1.getString(cursor1.getColumnIndex(Data.COLUMN_NodeName)).equals(region.getName())){
                            SensorTypeArray = cursor1.getString(cursor1.getColumnIndex(Data.COLUMN_SensorTypeArray));
                            sensorNum = cursor1.getInt(cursor1.getColumnIndex(Data.COLUMN_SensorNum));
                            a = false;
                        }
                    }while (cursor1.moveToNext() && a);
                }
                cursor1.close();
                db.close();

                bundle.putString(Data.COLUMN_Gateway, GatewayID);
                bundle.putString(Data.COLUMN_GatewayType, GatewayType);
                bundle.putString(Data.COLUMN_NodeName, region.getName());
                bundle.putInt(Data.COLUMN_SensorNum, sensorNum);
                bundle.putString(Data.COLUMN_SensorTypeArray, SensorTypeArray);
                System.out.println(SensorTypeArray);
                listener.OpenDataActivity(bundle);

            }
        });

        view.onFramesListener(new FramesListener() {
            @Override
            public void onRefresh(float number) {
                handler.obtainMessage(0, (int) number, 0).sendToTarget();
            }
        });
    }
}
